<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Auth\AuthenticationException;
class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Report or log an exception.
     *
     * @param  \Exception  $exception
     * @return void
     */
    public function report(Exception $exception)
    {
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
//        return parent::render($request, $exception);
        if ($exception) {
            return response()->view('error.'.$exception->getStatusCode(), [],$exception->getStatusCode());
        }
//        if ($exception instanceof HttpException) {
//            $code = $exception->getStatusCode();
//
//            if (view()->exists('errors.' . $code)) {
//                $message  = $exception->getMessage();
//                          return response()->view('errors.' . $exception->getStatusCode(), ['message'=>$message], $exception->getStatusCode());
//            }
//        }
        return parent::render($request, $exception);
    }

    protected function unauthenticated($request, AuthenticationException $exception)
    {
//        return $request->expectsJson()
//            ? response()->json(['message' => $exception->getMessage()], 401)
//            : redirect()->guest(route('login'));

//        获得当前守卫的值
        $guards = $exception->guards();
//        中间件
//        如果不是异步请求，就走这里
        if (in_array('admin',$guards)){
            $url = '/admin/login';
        }else{
            $url = '/deng';
        }

//        判断是不是异步请求
        if ($request->expectsJson()){
            return response()->json(['message' => $exception->getMessage()], 401);
        }else{
//            如果不是异步请求，走else
            return redirect()->guest($url);
        }
//        中间件写完，写用户列表
    }
}